<template>
  <div style="text-align: center">
    <el-tree
      :data="data"
      accordion
      :auto-expand-parent="false"
      node-key="id"
      show-checkbox
      :default-expanded-keys="open"
      :expand-on-click-node="false"
      :props="defaultProps"
      highlight-current
      ref="tree"
    ></el-tree>

    <el-row style="margin: 20px 0 0 0">
      <el-button type="primary" @click="addMenus()">确认分配</el-button>
      <el-button type="info" plain @click="closed()">取消分配</el-button>
    </el-row>
  </div>
</template>
<script>
import roleApi from "@/api/role";
import menuApi from "@/api/menu";
import { Message } from "element-ui";
export default {
  data() {
    const data = [];
    return {
      open: [], //展开节点
      data: JSON.parse(JSON.stringify(data)),
      data: JSON.parse(JSON.stringify(data)),
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      checkey: []
    };
  },
  props: {
    id: ""
  },
  created() {
    this.getMenuTree();
  },
  watch:{
    id:{
      handler(newVal){
        this.id = newVal
        this.getMenuTree()
      },
      immediate:true
    }
  },
  methods: {
    closed() {
      this.$refs.tree.setCheckedKeys([]);
      this.$emit("closeDialog");
      this.getMenuTree()
    },
    getcheckey() {
      let that = this;
      roleApi.getMenuByRoleIds(this.id).then(res => {
        res.data.data.forEach(id => {
          that.$refs.tree.setChecked(id, true, false);
        });
      });
    },
    //加载菜单树
    getMenuTree() {
      menuApi.getAllMenu().then(res => {
        this.data = res.data.data.tree;
        this.open = res.data.data.open;
        this.getcheckey();
      });
    },
    addMenus() {
      //获取子组件id数组
      this.checkey = this.$refs.tree.getCheckedKeys();
      //获取父组件id数组
      let treeParents = this.$refs.tree.getHalfCheckedKeys();
      this.checkey = this.checkey.concat(treeParents);
      roleApi.addMenus(this.checkey, this.id).then(res => {
        Message.success(res.message);
        this.closed();
      });
    }
  }
};
</script>
<style scoped>
</style>